package com.tbit.main.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * redis分布式锁工具类(搭配lua脚本实现)
 * @Author:BUGTian
 * @DATE: 2023/11/24
 */
@Component
public class RedisLockUtils {

    @Autowired
    private StringRedisTemplate redisTemplate;


    private static final Long SUCCESS = 1L;

    /**
     * 锁的超时时间（秒）
     */
    private static final long EXPIRE_TIME = 10;


    /**
     * 获取锁的等待时间（毫秒）
     */
    private static final long TIMOUT = 1000;

    /**
     * 释放锁lua脚本
     */
    private static final String UNLOCK_LUA = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";


    /**
     * 获取锁
     * @param key
     * @param value
     * @param expireTime 过期时间
     * @return
     */
    public Boolean lock(String key, String value, long expireTime) {
        try {
            Boolean tag = redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
            //获取锁成功
            return tag != null && tag;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 加锁（非阻塞）
     * @param key
     * @param value
     * @return
     */
    public Boolean lock(String key, String value) {
        long start = System.currentTimeMillis();
        try {
            for (; ; ) {
                Boolean tag = redisTemplate.opsForValue().setIfAbsent(key, value, EXPIRE_TIME, TimeUnit.SECONDS);
                if (tag != null && tag) {
                    //获取锁成功
                    return true;
                }
                //循环获取锁，timeout时间内仍未获取到锁则获取失败
                long time = System.currentTimeMillis() - start;
                if (time >= TIMOUT) {
                    return false;
                }
            }
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 解锁 （利用lua脚本保持原子性操作）
     * @param key
     * @param value
     * @return
     */
    public Boolean unlock(String key, String value) {
        RedisScript<String> redisScript = new DefaultRedisScript<>(UNLOCK_LUA, String.class);
        Object execute = redisTemplate.execute(redisScript, Collections.singletonList(key), value);
        if (execute != null && SUCCESS.equals(Long.parseLong(execute.toString()))) {
            return true;
        }
        return false;
    }
}
